<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/elementUi.css">
    <link rel="stylesheet" href="../css/global.css">
    <style>
        html::-webkit-scrollbar {
            display: none;
        }

        .el-card__body {
            padding: 16px;
        }

        .message {
            margin-top: 3px;
        }

        .message .el-card__body {
            padding: 10px;
        }

        .icon {
            border: 1px solid azure;
            box-shadow: 1px 1px 3px #CCCCCC;
            width: 40px;
            height: 40px;
            border-radius: 8px;
            margin-right: -5px;
        }

        .time {
            font-size: 12px;
            text-align: right;
            margin-right: 3%;
            margin-top: 3%;
            color: #666;
            display: flex;
            line-height: 20px;
            justify-content: space-between;
        }

        .lock_message {
            font-size: small;
            color: #4f4f4f
        }

        .lock_button {
            margin: auto;
            display: block
        }

        @font-face {
            font-family: 'iconfont';  /* Project id 2971702 */
            src: url('//at.alicdn.com/t/font_2971702_b118fqaiq8.woff2?t=1638110240929') format('woff2'),
            url('//at.alicdn.com/t/font_2971702_b118fqaiq8.woff?t=1638110240929') format('woff'),
            url('//at.alicdn.com/t/font_2971702_b118fqaiq8.ttf?t=1638110240929') format('truetype');
        }

        .black {
            color: #1d1c1c;
        }

        .del_button {
            float: right;
            font-size: 18px;
            color: #626262;
            margin-top: -12px;
            margin-right: -12px;

        }


        .smsList {
            overflow: scroll;
            width: 100%;
        }

        .smsList::-webkit-scrollbar {
            display: none;
        }

        #container::-webkit-scrollbar {
            display: none;
        }

        .code {
            font-size: 26px;
            width: 100%;
            align-content: center;
            text-align: center;
            font-weight: bolder;
        }

        .box-card {
            margin-bottom: 5px;
        }

        .source_text {
            font-size: 10px;
            color: #9c9797;
            margin-bottom: 5px;
        }

        .color-success {
            color: #67C23A;
        }

        .color-danger {
            color: #F56C6C;
        }

        .el-divider--horizontal {
            display: block;
            height: 1px;
            width: 100%;
            margin: 8px 0 3px 0;
        }
    </style>
</head>

<body>
<div id="container" style="height: 100%">

    <div>
        <div style="width: 292px;margin: auto auto 5px;">

            <el-button size="mini" :type="(connectStatus==='ed'?'primary':(connectStatus==='ing'?'warning':'error'))"
                       circle
                       @click="logout">
                <el-tooltip placement="bottom">
                    <div slot="content">退出登录</div>
                    <i class="el-icon-user"></i>
                </el-tooltip>
            </el-button>
            <el-button circle @click="clearSms" size="mini">
                <el-tooltip placement="bottom">
                    <div slot="content">清空消息</div>
                    <i class="el-icon-brush"> </i>
                </el-tooltip>

            </el-button>
            <el-button v-if="disabledStatus===false" size="mini" circle @click="lock">
                <el-tooltip placement="bottom">
                    <div slot="content">锁定</div>
                    <i class="el-icon-lock"></i>
                </el-tooltip>
            </el-button>
            <el-button v-if="disabledStatus===false" size="mini" circle @click="resetSecurity">
                <el-tooltip placement="bottom">
                    <div slot="content">重置秘钥</div>
                    <i class="el-icon-refresh"></i>
                </el-tooltip>
            </el-button>
            <el-select @visible-change="$forceUpdate()" @change="changeDevice" size="mini" style="width: 120px"
                       v-model="selectDevice" placeholder="">
                <template #prefix>
                <span style="padding-left: 3px; font-size: 15px;">
                  <template v-if="deviceInfo[selectDevice.toString()]&&deviceInfo[selectDevice.toString()].pushState">
                            <i style="padding-top: 6px;" class="el-icon-success color-success"></i>
                        </template>
                        <template v-else>
                            <i style="padding-top: 6px;" class="el-icon-remove color-danger"></i>
                        </template>
                </span>
                </template>
                <el-option
                        v-for="item in deviceList"
                        :key="item.name"
                        :label="item.label"
                        :value="item.name">
                    <span style="float: left">
                        <template v-if="deviceInfo[item.name.toString()].pushState">
                            <i class="el-icon-success color-success"></i>
                        </template>
                        <template v-else>
                            <i class="el-icon-remove color-danger"></i>
                        </template>
                    </span>
                    <span style="padding-left: 6px">{{item.label}}</span>
                </el-option>
            </el-select>


        </div>
        <template v-if="disabledStatus===false">
            <el-progress style="margin-bottom: 10px" :width="88" :text-inside="true" :stroke-width="20"
                         :format="levelFormat"
                         :percentage="batteryLevel"
                         :color="color"></el-progress>
            <div class="smsList">
                <template v-if="groups.length>0">
                    <template v-for="(item,item_index) in groups">
                        <el-card v-if="item.type==='extract_sms'" class="box-card" shadow="hover">
                            <i @click="del(item_index)" class="el-icon-error del_button"></i>
                            <div style="width: 100%; text-align: center;font-size:20px;font-weight: bolder;">
                                {{item.title}}
                            </div>
                            <div style="font-size: 13px;color: #9c9797">{{item.mainContent.key}}</div>
                            <div class="code">{{item.mainContent.text}}</div>

                            <el-divider v-if="!item.showContent"></el-divider>


                            <div style="font-size: 13px;margin-top: 6px;color: #9c9797" v-for="(kv) in item.param">
                                {{kv.key}} &nbsp;&nbsp;<span class="black">{{kv.text}}</span></div>

                            <el-divider v-if="item.showContent"></el-divider>
                            <div v-if="item.showContent" class="source_text"> *{{item.content}}</div>
                            <el-button v-if="item.copyMain === true" style="width: 100%" type="primary"
                                       @click="copyCode(item.mainContent.text)" size="mini">
                                复制验证码
                            </el-button>
                            <div class="time">
                                <el-tag size="mini">{{item.alias}}</el-tag>
                                <span>{{item.time}}</span>
                            </div>
                        </el-card>
                        <el-card v-else-if="item.type==='PHONE_NOTIFICATION'" class="box-card">
                            <div>
                                <i @click="del(item_index)" class="el-icon-error del_button"></i>
                                <div>
                                    <div style="float: left">

                                        <el-badge :value="item.unreadCount" :max="9" :hidden="item.unreadCount<=0"
                                                  class="item">
                                            <img @click="changeFold(item_index)" class="icon"
                                                 :src="item.iconBase64">
                                        </el-badge>
                                    </div>
                                    <div>
                                        <el-tooltip class="item" effect="dark" :content="item.title" placement="top">
                                            <div style=" padding-bottom: 7px;padding-left:20px;font-weight: bolder; line-height: 17px; overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
                                                {{item.title}}
                                            </div>
                                        </el-tooltip>
                                        <el-tooltip class="item" effect="dark" :content="item.content" placement="top">
                                            <div style="font-size:15px;padding-left:20px;line-height: 23px;padding-right: 10px;;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
                                                {{item.content}}
                                            </div>
                                        </el-tooltip>


                                    </div>
                                </div>

                                <el-divider v-if="item.isFold&&item.messageList.length>1"></el-divider>
                                <div class="time" style="margin-top: 1%">
                                    <el-tag size="mini">{{item.alias}}</el-tag>
                                    <span>{{item.time}}</span>
                                </div>

                                <template v-if="item.isFold&& item.messageList.length>1">
                                    <template v-for="(message,message_index) in item.messageList">
                                        <el-card class="message" v-if="message_index>=1">
                                            <div>
                                                <div style="font-size:15px;line-height: 23px;">
                                                    {{item.foldType === 1 ? message.secret.content :
                                                    message.secret.title}}
                                                </div>
                                            </div>
                                            <div class="time"
                                                 style="margin-top: 2%;justify-content: end!important;width: 100%!important; line-height: 1px;">
                                                <span>{{message.time}}</span>
                                            </div>
                                        </el-card>
                                    </template>
                                </template>


                            </div>
                        </el-card>
                        <el-card v-else class="box-card">

                            <img :src="item.iconBase64">
                            <i @click="del(item_index)" class="el-icon-error del_button"></i>
                            <div style="width: 100%; font-size:20px;font-weight: bolder;">{{item.address}}</div>
                            <el-divider></el-divider>
                            <div style="font-size:15px">{{item.content}}</div>
                            <el-button v-if="item.address=='来自剪贴板的内容:'" style="width: 100%" type="primary"
                                       @click="copyCode(item.content)" size="mini">复制到剪贴板
                            </el-button>
                            <div class="time">

                                <el-tag size="mini">{{item.alias}}</el-tag>
                                <span>{{item.time}}</span>
                            </div>

                        </el-card>
                    </template>
                </template>
                <el-card v-if="groups.length<=0 && loading_status ===false"
                         style="text-align: center;color: #8c939d;height: 267px" shadow="always">
                    <i style="margin-top: 50px;font-size: 60px" class="el-icon-chat-line-round"></i>
                    <p>还没有收到任何消息</p>
                </el-card>
            </div>
        </template>
        <template v-else>
            <el-card v-if="loading_status ===false" style="text-align: center;height: 295px" shadow="always">
                <i style="margin-top: 50px;font-size: 60px" class="el-icon-lock"></i>
                <p class="lock_message">你可以在手机APP的 设备管理 中解锁设备</p>
                <el-button class="lock_button" @click="requestUnlock" type="success" size="mini">在手机上解锁</el-button>

            </el-card>
        </template>
    </div>
    <!--    <div>-->
    <!--        <p>秘钥更新时间:2021-10-03 10:24</p>-->
    <!--    </div>-->


</div>

</body>

<script src="../js/jquery.min.js"></script>
<script src="../js/util.js" type="module"></script>
<script src="../js/vue.js"></script>
<script src="../js/app.js"></script>
<script src="../js/elementUi.js"></script>

<script type="module">
    import {
        resolveSMSContent,
        newKeyPair,
        getStorage,
        getDeviceId,
        showLoading,
        decodeMessage,
        setStorage,
        network,
        dataURLtoFile, getHttpPath, getWebSocketPath,
        sendNotification, removeStorage, writeContentToClipBoard, quitApp, formatTime
    } from "../js/util.js";


    let vm = new Vue({
        el: "#container",
        data: {
            deviceInfo: [],
            appConfig: {
                "com.tencent.mm": 1
            },
            fold: false,
            selectDevice: '',
            deviceList: [],
            // batteryInfo: [],
            //ed/ing/out
            connectStatus: "ing",
            groups: [],
            ws: "",
            batteryLevel: 0,
            loading_status: true,
            status: "",
            chargeStatus: "未知",
            color: '',
            lastBeatTime: '',
            lockReconnect: false,
            beatInterval: '',
            disabledStatus: JSON.parse(getStorage("disabled")),
            updateSecurityTime: '',
        },
        mounted: function () {
            let that = this;
            showLoading(that, "正在生成秘钥对...", 15)
            this.$nextTick(function () {
                setTimeout(function () {
                    that.loading_status = true;
                    newKeyPair(that);
                    that.updateSecurityTime = new Date();
                    that.connectToServer();
                    that.chargeStatus = false
                    that.showColor()
                    that.loading_status = false;
                    setTimeout(function () {
                        that.resetSecurity();
                    }, 1000 * 60 * 60);
                }, 500)
            })
        },
        methods: {
            changeDevice() {
                let temBatteryInfo = this.deviceInfo[this.selectDevice.toString()].batteryInfo[this.deviceInfo[this.selectDevice.toString()].batteryInfo.length - 1];
                if (typeof temBatteryInfo === 'undefined') {
                    return;
                }
                this.batteryLevel = temBatteryInfo.batteryLevel;
                this.chargeStatus = temBatteryInfo.chargeStatus;
                this.showColor();
            },
            changeFold(index) {
                this.groups[index].isFold = !this.groups[index].isFold
                this.groups[index].unreadCount = 0;
            },
            clearSms() {
                this.groups.splice(0, this.groups.length);
            },
            addToDeviceList(device) {
                let exist = false;
                let existIndex = -1;
                for (let i = 0; i < this.deviceList.length; i++) {
                    let d = this.deviceList[i];
                    if (d.name === device.id) {
                        if (this.deviceList[i].alias !== device.alias) {
                            existIndex = i;
                        }
                        exist = true;

                    }
                }
                if (existIndex !== -1) {
                    this.deviceList.splice(existIndex, 1);
                    exist = false;
                }
                if (exist !== true) {
                    this.deviceList.push({
                        name: device.id,
                        label: device.alias
                    })
                    if (this.selectDevice === '') {
                        this.selectDevice = device.id;
                    }
                    if (typeof this.deviceInfo[device.id] === 'undefined') {
                        this.deviceInfo[device.id] = {batteryInfo: [], pushState: true}
                    }
                }
                this.$forceUpdate()
            },
            requestUnlock() {
                network(getHttpPath() + '/device/request/unlock', "POST", {}, function (data) {
                    console.log("已经发送解锁请求")
                }, function (event, data) {
                })
            },
            lock() {
                let url = getHttpPath() + '/device/status';
                network(url, "PUT", {
                    deviceId: getStorage("deviceId"),
                    lock: true
                }, function (data) {
                }, function (event, data) {
                })
            },
            resetSecurity() {
                let that = this;
                that.loading_status = true;
                showLoading(that, "正在重置秘钥对...")
                setTimeout(function () {
                    newKeyPair(that);
                    that.loading_status = false;
                    that.updateSecurityTime = new Date();
                }, 100);


            },
            copyCode(content) {
                writeContentToClipBoard(content)
            },
            quit() {
                this.logout();
                quitApp();
            },
            logout() {
                let url = getHttpPath() + '/api/logout';
                network(url, "GET", {}, function () {
                }, function () {
                });
                removeStorage("userId");
                removeStorage("token");
                removeStorage("privateKey");
                removeStorage("privateKey");
                window.location.href = "login.html";
            },
            //发送心跳
            heartBeat() {
                let that = this
                clearInterval(that.beatInterval);
                that.beatInterval = setInterval(function () {
                    //状态监测
                    console.log("状态监测")
                    let now = new Date().getTime();
                    if (that.ws.readyState === 1) {
                        that.ws.send("beat");
                        return;
                    }
                    if (now - that.lastBeatTime > 10 * 1000) {
                        that.connectToServer()
                    }

                }, 5000)
            },
            //收到服务器的通用消息
            receiveCommonMessage(data) {
                let that = this;
                that.lastBeatTime = new Date().getTime();
                if (data.type === 'BEAT') {
                    return;
                }
                if (data.type === 'OFFLINE') {
                    that.ws.close();
                    removeStorage("token")
                    removeStorage("userId")
                    removeStorage("privateKey")
                    sendNotification("温馨提示", "登录退出，请注意", "")
                    window.location.href = "login.html";
                    return;
                }
                if (data.type === "DISABLED") {
                    //设备禁用状态
                    let lockStatus = data.nonEncrypted.lockStatus
                    that.disabledStatus = lockStatus;
                    setStorage("disabled", lockStatus)
                    return;
                }
                if (data.type === "PUSH_STATE_CHANGE") {
                    if (typeof that.deviceInfo[data.nonEncrypted.deviceId.toString()] === 'undefined') {
                        that.deviceInfo[data.nonEncrypted.deviceId.toString()] = {
                            pushState: data.nonEncrypted.pushState,
                            batteryInfo: []
                        }
                    } else {
                        that.deviceInfo[data.nonEncrypted.deviceId.toString()].pushState = data.nonEncrypted.pushState;
                        that.$forceUpdate();
                    }
                }
                console.log("处理完毕")
            },


            //收到服务器转发的数据
            receiveServerMessage(data) {
                let that = this;
                let msg = {};
                msg.alias = data.fromDevice.alias;
                msg.deviceId = data.fromDevice.id;
                msg.time = formatTime(data.time);
                msg.type = data.type;
                msg.secret = decodeMessage(data.secret);
                msg.nonEncrypted = data.nonEncrypted;
                switch (msg.type) {
                    case 'SMS': {
                        let url = getHttpPath() + '/config/extract/rules';
                        network(url, "POST", {
                            deviceId: getStorage("deviceId")
                        }, function (data) {
                            that.receiveSms(msg, data.data);
                        }, function (event, data) {
                        })
                        break;
                    }
                    case 'BATTERY_LEVEL': {
                        this.receiveBatteryMsg(msg);
                        break;
                    }
                    case 'CLIP_BOARD': {
                        this.receiveClipBoard(msg);
                        break;
                    }
                    case 'PHONE_NOTIFICATION': {
                        this.receivePhoneNotification(msg);
                    }
                }

            },
            //建立websocket连接
            connectToServer() {
                if (this.lockReconnect) {
                    return;
                }
                console.log("正在尝试重新连接")
                this.connectStatus = "ing"
                this.lockReconnect = true;
                try {
                    this.ws = new WebSocket(getWebSocketPath() + "/webSocket/" + getStorage('token') + "/" + getStorage('deviceId'));
                } catch (e) {
                    that.lockReconnect = false
                    console.log(e);
                }
                let that = this;
                this.ws.onopen = function () {
                    // Web Socket 已连接上，使用 send() 方法发送数据
                    that.connectStatus = "ed"
                    that.lastBeatTime = new Date().getTime();
                    try {
                        that.ws.send('beat');
                    } catch (e) {
                    }

                    that.connectStatus = 'ed'
                    // 持续发送心跳包
                    that.heartBeat();
                    that.lockReconnect = false;
                };
                this.ws.onmessage = function (evt) {
                    try {
                        that.lastBeatTime = new Date().getTime();
                        let receivedMsg = evt.data;
                        let data = JSON.parse(receivedMsg);
                        if (data.code === 105) {
                            that.receiveCommonMessage(data)
                            return;
                        }
                        if (that.loading_status === true) {
                            return;
                        }
                        console.log(data.fromDevice.alias)
                        that.addToDeviceList(data.fromDevice);
                        that.receiveServerMessage(data);
                    } catch (e) {
                        console.log(e);
                    }
                };
                this.ws.onclose = function () {
                    // 关闭 websocket
                    that.ws = '';
                    that.connectStatus = 'out'
                    that.lockReconnect = false;
                };
                this.ws.onerror = function () {
                    that.connectStatus = 'out'
                    that.lockReconnect = false;
                    that.connectToServer();

                }
            },
            /**
             * 处理收到的短信
             * @param msg
             */
            receiveSms(msg, extractRules) {
                //尝试解析内容，尝试解析来源和验证码
                let result = resolveSMSContent(msg.secret.content, extractRules);

                if (result === '') {
                    result = msg;
                    msg.content = msg.secret.content;
                    msg.address = msg.secret.address;
                    result.type = "text_sms"
                } else {
                    result.type = "extract_sms"
                }
                result.alias = msg.alias;
                this.groups.unshift(result);
                if (msg.iconBase64 !== '') {
                    sendNotification(msg.secret.address, msg.secret.content, formatTime(msg.time), msg.iconBase64);
                } else {
                    sendNotification(msg.secret.address, msg.secret.content, formatTime(msg.time));

                }

            },
            /**
             * 处理收到的剪贴板内容
             * @param msg
             */
            receiveClipBoard(msg) {
                msg.address = "来自剪贴板的内容:";
                msg.content = msg.secret.content
                this.groups.unshift(msg);
                writeContentToClipBoard(msg.content);
            },
            receivePhoneNotification(msg) {
                msg.iconBase64 = msg.nonEncrypted.icon


                let temMsg = null;
                if (this.appConfig[msg.secret.pkg] === 1) {
                    let uniqueKey = msg.secret.pkg + "/" + msg.secret.title;

                    for (let i = 0; i < this.groups.length; i++) {
                        if (uniqueKey === this.groups[i].uniqueKey) {
                            temMsg = this.groups[i];
                            this.groups.splice(i, 1);
                            break;
                        }
                    }
                    if (temMsg == null) {
                        temMsg = {
                            iconBase64: msg.iconBase64,
                            type: 'PHONE_NOTIFICATION',
                            isFold: false,
                            foldType: 1,//折叠的类型 0 按应用，1 按标题
                            uniqueKey: uniqueKey,
                            messageList: [],
                            unreadCount: 0
                        }

                    }
                } else {
                    let uniqueKey = msg.secret.pkg;
                    for (let i = 0; i < this.groups.length; i++) {
                        if (uniqueKey === this.groups[i].uniqueKey) {
                            temMsg = this.groups[i];
                            this.groups.splice(i, 1);
                            break;
                        }
                    }
                    if (temMsg == null) {
                        temMsg = {
                            iconBase64: msg.iconBase64,
                            type: 'PHONE_NOTIFICATION',
                            isFold: false,
                            foldType: 0,//折叠的类型 0 按应用，1 按标题
                            uniqueKey: uniqueKey,
                            messageList: [],
                            unreadCount: 0
                        }

                    }
                }
                this.groups.unshift(temMsg);
                temMsg.iconBase64 = msg.iconBase64;
                temMsg.title = msg.secret.title;
                temMsg.alias = msg.alias;
                temMsg.content = msg.secret.content;
                temMsg.unreadCount = temMsg.unreadCount + 1;
                temMsg.messageList.unshift(msg);
                sendNotification(msg.secret.title, msg.secret.content, formatTime(msg.time), msg.nonEncrypted.icon)
            },
            /**
             * 处理收到的剪贴板内容
             * @param msg
             */
            receiveBatteryMsg(msg) {
                // setStorage("batteryLevel", Number(msg.level));
                // setStorage("chargeStatus", msg.status);
                if (this.selectDevice === msg.deviceId) {
                    this.batteryLevel = Number(msg.secret.level);
                    this.chargeStatus = msg.secret.status;
                }
                let last = this.deviceInfo[msg.deviceId.toString()].batteryInfo[this.deviceInfo[msg.deviceId.toString()].batteryInfo.length - 1];

                // 分设备保存电量数据
                if (typeof this.deviceInfo[msg.deviceId.toString()] === 'undefined') {
                    this.deviceInfo[msg.deviceId.toString()] = {batteryInfo: []}
                }
                this.deviceInfo[msg.deviceId.toString()].batteryInfo.push({
                    "batteryLevel": Number(msg.secret.level),
                    "chargeStatus": msg.secret.status
                })

                if (typeof last !== "undefined" && last.chargeStatus !== msg.secret.status) {
                    sendNotification("温馨提示", msg.alias + (msg.secret.status === true ? '开始充电' : "充电断开"), formatTime(msg.time))
                }
                this.showColor();
            },
            del(index) {
                this.groups.splice(index, 1);
            },
            levelFormat(percent) {
                if (this.chargeStatus) {
                    return "充电中\n" + percent + "%";
                } else {
                    return percent + "%"
                }
            },
            showColor() {
                let level = Number(this.batteryLevel)
                if (this.chargeStatus) {
                    this.color = '#5fca71';
                    return;
                }
                if (level < 20) {
                    this.color = '#ba4540';
                } else {
                    this.color = '#4aa0f8';
                }

            }


        }


    })
</script>

</html>
